//------------------------------------------------------------------- // Purpose: Compare the speed of two algoritms for finding the closest // pair of points in an array of points. The brute force // method compares every point to every other point. The // recursive method splits the points based on x coordinate, // finds the closest pair of points in each half, and then // combines the results to get the solution. // // Author: John Gauch //------------------------------------------------------------------- #include #include #include using namespace std; const int MAX_SIZE = 10000; int sqrt_count = 0; //------------------------------------------------------------------- // Simple (x,y) point class. //------------------------------------------------------------------- class Point { public: int x,y; }; //------------------------------------------------------------------- // Array of point class. //------------------------------------------------------------------- class PointArray { public: void random(int range); void print(); void xsort(); void ysort(); Point point[MAX_SIZE]; int size; }; //------------------------------------------------------------------- // Assign random values to array of points. //------------------------------------------------------------------- void PointArray::random(int count) { size = count; int range = size * 10; for (int i=0; i point[j].x) || ((point[i].x == point[j].x) && (point[i].y > point[j].y))) { Point temp = point[i]; point[i] = point[j]; point[j] = temp; } } //------------------------------------------------------------------- // Sort array of points in y direction //------------------------------------------------------------------- void PointArray::ysort() { for (int i=0; i point[j].y) || ((point[i].y == point[j].y) && (point[i].x > point[j].x))) { Point temp = point[i]; point[i] = point[j]; point[j] = temp; } } //------------------------------------------------------------------- // Brute force algorithm to find closest pair of points. //------------------------------------------------------------------- void closest_pair(PointArray &pts, Point &p1, Point &p2, double &dist) { dist = MAX_SIZE; for (int i=0; i